﻿using ManagementSystem.App_LocalResources;
using ManagementSystem.Filter;
using ManagementSystem.Models;
using MS.Cache;
using MS.Entities;
using MS.Enums.Common;
using MS.Identity;
using MS.Logic;
using MS.Utility.Common;
using ServiceStack.Caching;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ManagementSystem.Areas.BMS.Controllers
{
    public class LoginController : Controller
    {
        // GET: BMS/Login

        public ActionResult Index()
        {
            if (SecurityIdentity.GetLoginUid(Platform.BMS) > 0)
            {
                return Redirect("/BMS");
            }

            return View();
        }
        /// <summary>
        /// 获取滑块验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSilderCodeImage(string uuid)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            int offsetX = 0;
            byte[] imgBuffer = ValidateCodeHelper.CreateSilderCodeImage(out offsetX, Path.Combine(path, "Scripts/lib/sildercode/bg"), Path.Combine(path, "Scripts/lib/sildercode/img/mark.png"), Path.Combine(path, "Scripts/lib/sildercode/img/mark2.png"));
            CacheAdapter.Cache.Add<int>(uuid, offsetX);

            return File(imgBuffer, "image/png");
        }

        /// <summary>
        /// 检查滑块验证码
        /// </summary>
        /// <param name="userOffsetX"></param>
        /// <returns></returns>
        public ActionResult CheckSilderCode(double userOffsetX, string uuid)
        {
            int offsetX = CacheAdapter.Cache.Get<int>(uuid);
            if (ValidateCodeHelper.CheckSilderCode(Convert.ToInt32(Math.Round(userOffsetX)), offsetX) == 1)
            {
                return Content("ok");
            }
            return Content("error");
        }
        /// <summary>
        /// 使用用户名和密码登陆
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Login(string account, string password)
        {
            JsonResultModel model = new JsonResultModel();
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                return Json(model);
            }

            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            LoginResult loginResult = userAccountLogic.Login(account, password, MS.Enums.Common.Platform.BMS);
            switch (loginResult)
            {
                case LoginResult.Success:
                    model.code = Code.SUCCESS;
                    model.message = Message.SUCCESS;
                    break;
                case LoginResult.Fail:
                    model.code = Code.ERROR;
                    model.message = Message.LOGINFAIL;
                    break;
                case LoginResult.IllegalLogin:
                    model.code = Code.UNAUTHORITY;
                    model.message = Message.USERSTATUSSTOP;
                    break;
            }
            model.data = new { };
            return Json(model);
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            SecurityIdentity.Logout();
            return Redirect("/BMS/Login");
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="comfirmPassword">确认密码</param>
        /// <returns></returns>
        [HttpPost]
        [LoginFilter(Platform.BMS)]
        public JsonResult ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            JsonResultModel model = new JsonResultModel();
            if (string.IsNullOrEmpty(oldPassword) || string.IsNullOrEmpty(newPassword) || string.IsNullOrEmpty(confirmPassword))
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = Message.PARAMERROR;
                return Json(model);
            }

            if(newPassword != confirmPassword)
            {
                model.code = Code.ERROR;
                model.message = Message.ERROR;
                model.data = "两次密码输入不一致";
                return Json(model);
            }

            long uid = SecurityIdentity.GetLoginUid();
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAccount userAccount = userAccountLogic.GetById(uid);
            string md5OldPassword = Utils.MD5(oldPassword);
            string md5NewPassword = Utils.MD5(newPassword);

            if((userAccount.Passformat==(int)Passformat.Plaintext && userAccount.Password != oldPassword)||(userAccount.Passformat == (int)Passformat.Encrypt && userAccount.Password != md5OldPassword))
            {
                model.code = Code.ERROR;
                model.message = Message.ERROR;
                model.data = "原始密码错误！";
                return Json(model);
            }

            userAccount.Password = md5NewPassword;
            userAccount.Passformat = (int)Passformat.Encrypt;
            userAccount.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAccount.UpdateUid = uid;
            userAccountLogic.Save(userAccount);
            userAccountLogic.RemoveCache(uid);

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            return Json(model);
        }
    }
}